<template>
    <el-config-provider :locale="locale">
   <div class="post-management-container">
     <!-- 统一标题样式 -->
     <div class="header-section">
       <h2>帖子管理</h2>
       <div class="title-line"></div>
     </div>
     
     <!-- 搜索框卡片 -->
     <el-card class="filter-card">
       <div class="filter-content">
         <el-input 
           v-model="contentQuery" 
           placeholder="搜索帖子内容" 
           @keyup.enter="handleSearch"
           clearable
           style="width: 400px;">
           <template #prepend>
             <el-icon><Search /></el-icon>
           </template>
         </el-input>
         
         <div class="filter-actions">
           <el-button 
             class="custom-primary-button"
             type="primary" 
             @click="handleSearch">
             搜索
           </el-button>
           <el-button 
             class="custom-reset-button"
             @click="resetSearch">
             重置
           </el-button>
         </div>
       </div>
     </el-card>
     
     <!-- 帖子列表卡片 -->
     <el-card class="post-list-card">
       <div class="list-header">
         <div class="header-gradient"></div>
         <h3>帖子列表</h3>
         <div class="total-posts">
           共 <span class="highlight">{{ total || 0 }}</span> 篇帖子
         </div>
       </div>
       
       <el-table :data="posts" stripe style="width: 100%" class="post-table">
         <el-table-column prop="title" label="标题" min-width="180"></el-table-column>
         <el-table-column prop="username" label="作者" width="130"></el-table-column>
         <el-table-column label="创建时间" width="180">
           <template #default="scope">
             {{ formatDateTime(scope.row.createdAt) }}
           </template>
         </el-table-column>
         <el-table-column prop="likeCount" label="点赞数" width="100" align="center"></el-table-column>
         <el-table-column prop="commentCount" label="评论数" width="100" align="center"></el-table-column>
         <el-table-column label="状态" width="120">
           <template #default="scope">
             <el-tag 
               :type="scope.row.status === 1 ? 'success' : 'danger'"
               effect="dark"
               round
               class="status-tag-table">
               {{ scope.row.status === 1 ? '正常' : '已删除' }}
             </el-tag>
           </template>
         </el-table-column>
         <el-table-column label="操作" width="260">
           <template #default="scope">
             <div class="action-buttons">
               <el-button
                 class="detail-button"
                 link
                 type="primary"
                 size="small"
                 @click.stop="handleViewDetail(scope.row)">
                 <el-icon><View /></el-icon> 查看详情
               </el-button>
               <el-button
                 class="delete-button"
                 link
                 type="danger"
                 size="small"
                 @click.stop="handleDelete(scope.row.postId)"
                 v-if="scope.row.status === 1">
                 <el-icon><Delete /></el-icon> 删除
               </el-button>
               <el-button
                 class="restore-button"
                 link
                 type="success"
                 size="small"
                 @click.stop="handleRestore(scope.row.postId)"
                 v-if="scope.row.status === 0">
                 <el-icon><RefreshRight /></el-icon> 恢复
               </el-button>
             </div>
           </template>
         </el-table-column>
       </el-table>
       
       <!-- 分页控件 -->
       <div class="pagination-container">
         <el-pagination
           @size-change="handleSizeChange"
           @current-change="handleCurrentChange"
           :current-page="currentPage"
           :page-sizes="[5, 10, 20]"
           :page-size="pageSize"
           :background="true"
           layout="total, sizes, prev, pager, next, jumper"
           :total="total"
         />
       </div>
     </el-card>
     
     <!-- 帖子详情弹窗 -->
     <el-dialog
       v-model="dialogVisible"
       title="帖子详情"
       width="70%"
       class="post-detail-dialog"
       :before-close="handleClose">
       <div class="post-detail-card">
         <div class="post-header">
           <h3 class="post-title">{{ currentPost.title }}</h3>
           <el-tag 
             :type="currentPost.status === 1 ? 'success' : 'danger'" 
             effect="dark"
             class="status-tag">
             {{ currentPost.status === 1 ? '正常' : '已删除' }}
           </el-tag>
         </div>
         
         <el-divider />
         
         <div class="post-meta-grid">
           <div class="meta-item">
             <span class="meta-label">作者：</span>
             <span class="meta-value">{{ currentPost.username || '未知用户' }}</span>
           </div>
           <div class="meta-item">
             <span class="meta-label">创建时间：</span>
             <span class="meta-value">{{ formatDateTime(currentPost.createdAt) }}</span>
           </div>
           <div class="meta-item">
             <span class="meta-label">点赞数：</span>
             <span class="meta-value">{{ currentPost.likeCount || 0 }}</span>
           </div>
           <div class="meta-item">
             <span class="meta-label">评论数：</span>
             <span class="meta-value">{{ currentPost.commentCount || 0 }}</span>
           </div>
         </div>
         
         <div class="post-content">
           <h4>帖子内容</h4>
           <div class="content-box">
             {{ currentPost.content }}
           </div>
         </div>
         
         <!-- 评论列表 -->
         <div class="comments-section">
           <h4>评论列表</h4>
           <el-table :data="comments" stripe style="width: 100%" class="comments-table">
             <el-table-column prop="content" label="评论内容"></el-table-column>
             <el-table-column label="评论者" width="150">
               <template #default="scope">
                 {{ scope.row.username || '未知用户' }}
               </template>
             </el-table-column>
             <el-table-column label="评论时间" width="180">
               <template #default="scope">
                 {{ formatDateTime(scope.row.createdAt) }}
               </template>
             </el-table-column>
             <el-table-column label="状态" width="100">
               <template #default="scope">
                 <el-tag 
                   :type="scope.row.status === 1 ? 'success' : 'danger'"
                   effect="dark"
                   round>
                   {{ scope.row.status === 1 ? '正常' : '已删除' }}
                 </el-tag>
               </template>
             </el-table-column>
             <el-table-column label="操作" width="150">
               <template #default="scope">
                 <div class="comment-actions">
                   <el-button
                     class="delete-comment-button"
                     link
                     type="danger"
                     size="small"
                     @click="deleteComment(scope.row.commentId)"
                     v-if="scope.row.status === 1">
                     删除
                   </el-button>
                   <el-button
                     class="restore-comment-button"
                     link
                     type="success"
                     size="small"
                     @click="restoreComment(scope.row.commentId)"
                     v-if="scope.row.status === 0">
                     恢复
                   </el-button>
                 </div>
               </template>
             </el-table-column>
           </el-table>
         </div>
       </div>
       
       <template #footer>
         <div class="dialog-footer">
           <el-button @click="dialogVisible = false">关闭</el-button>
         </div>
       </template>
     </el-dialog>
   </div>
     </el-config-provider>
 </template>
 
 <script setup>
 import { ref, onMounted } from 'vue';
 import axios from 'axios';
 import { ElMessage, ElMessageBox } from 'element-plus';
 import { Search, View, Delete, RefreshRight } from '@element-plus/icons-vue';
 // 确保正确导入中文包
 import zhCn from 'element-plus/es/locale/lang/zh-cn';
 
 // 定义locale变量
 const locale = ref(zhCn);
 // 搜索参数
 const contentQuery = ref('');
 
 // 帖子数据
 const posts = ref([]);
 const total = ref(0);
 
 // 分页状态
 const currentPage = ref(1);
 const pageSize = ref(10);
 
 // 评论数据
 const comments = ref([]);
 const totalComments = ref(0);
 const commentPage = ref(1);
 const commentSize = ref(10);
 const selectedPostId = ref(null);
 const selectedPostTitle = ref('');
 
 // 弹窗状态
 const dialogVisible = ref(false);
 const currentPost = ref({});
  
 // 日期格式化函数
 const formatDateTime = (dateTime) => {
   if (!dateTime) return '无';
   const date = new Date(dateTime);
   if (isNaN(date.getTime())) return '无效日期';
   return date.toLocaleString('zh-CN', {
     year: 'numeric',
     month: '2-digit',
     day: '2-digit',
     hour: '2-digit',
     minute: '2-digit',
     second: '2-digit'
   });
 };
 
 // 获取帖子列表
 const fetchPosts = async () => {
   try {
     const response = await axios.get('/api/post-management', {
       params: {
         content: contentQuery.value,
         page: currentPage.value - 1,
         size: pageSize.value
       }
     });
     console.log('API response:', response.data);
     
     if (response.data.content) {
       posts.value = response.data.content.map(post => ({
         ...post,
         postId: post.post_id || post.postId,
         createdAt: post.created_at || post.createdAt || post.createTime,
         username: post.username || '未知用户',
         likeCount: post.like_count || 0,
         commentCount: post.comment_count || 0
       }));
       total.value = response.data.totalElements;
     }
     console.log('Processed posts:', posts.value);
   } catch (error) {
     console.error('获取帖子列表失败:', error);
     ElMessage.error('获取帖子列表失败，请重试');
   }
 };
 
 // 获取评论列表
 const fetchComments = async () => {
   if (!selectedPostId.value) return;
   try {
     const response = await axios.get(`/api/post-management/${selectedPostId.value}/comments`);
     console.log('Comments response:', response.data);
     
     if (Array.isArray(response.data)) {
       comments.value = response.data.map(comment => ({
         ...comment,
         createdAt: comment.createTime,
         username: comment.username || '未知用户'
       }));
       totalComments.value = response.data.length;
     }
   } catch (error) {
     console.error('获取评论失败:', error);
     ElMessage.error('获取评论失败，请重试');
   }
 };
 
 // 搜索处理
 const handleSearch = () => {
   currentPage.value = 1; // 重置页码
   fetchPosts();
 };
 
 // 重置搜索
 const resetSearch = () => {
   contentQuery.value = '';
   currentPage.value = 1; // 重置页码
   fetchPosts();
 };
  
 // 显示评论列表
 const showComments = (row) => {
   selectedPostId.value = row.postId;
   selectedPostTitle.value = row.title;
   commentPage.value = 1;
   fetchComments();
 };
 
 // 删除评论
 const deleteComment = async (commentId) => {
   try {
     await ElMessageBox.confirm('确定要删除这个评论吗？', '提示', {
       confirmButtonText: '确定',
       cancelButtonText: '取消',
       type: 'warning'
     });
 
     const response = await axios.delete(`/post-comment/${commentId}`);
     if (response.status === 200) {
       await fetchComments();
       ElMessage.success('评论删除成功');
     } else {
       ElMessage.error('删除失败，请重试');
     }
   } catch (error) {
     if (error !== 'cancel') {
       console.error('删除评论失败:', error);
       ElMessage.error('操作失败，请联系管理员');
     }
   }
 };
 
 // 恢复评论
 const restoreComment = async (commentId) => {
   try {
     await ElMessageBox.confirm('确定要恢复这个评论吗？', '提示', {
       confirmButtonText: '确定',
       cancelButtonText: '取消',
       type: 'info'
     });

     const response = await axios.put(`/post-comment/restore/${commentId}`);
     if (response.status === 200) {
       await fetchComments();
       ElMessage.success('评论恢复成功');
     } else {
       ElMessage.error('恢复失败，请重试');
     }
   } catch (error) {
     if (error !== 'cancel') {
       console.error('恢复评论失败:', error);
       ElMessage.error('操作失败，请联系管理员');
     }
   }
 };
 
 // 删除帖子
 const handleDelete = async (postId) => {
   try {
     await ElMessageBox.confirm('确定要删除这个帖子吗？', '提示', {
       confirmButtonText: '确定',
       cancelButtonText: '取消',
       type: 'warning'
     });
     
     await axios.delete(`/api/post-management/${postId}`);
     await fetchPosts();
     ElMessage.success('帖子删除成功');
   } catch (error) {
     if (error !== 'cancel') {
       console.error('删除帖子失败:', error);
       ElMessage.error('操作失败，请联系管理员');
     }
   }
 };
 
 // 恢复帖子
 const handleRestore = async (postId) => {
   try {
     await ElMessageBox.confirm('确定要恢复这个帖子吗？', '提示', {
       confirmButtonText: '确定',
       cancelButtonText: '取消',
       type: 'info'
     });
     
     await axios.put(`/api/post-management/restore/${postId}`);
     await fetchPosts();
     ElMessage.success('帖子恢复成功');
   } catch (error) {
     if (error !== 'cancel') {
       console.error('恢复帖子失败:', error);
       ElMessage.error('操作失败，请联系管理员');
     }
   }
 };
 
 // 查看详情
 const handleViewDetail = async (post) => {
   try {
     console.log('Viewing post:', post);
     if (!post.postId) {
       ElMessage.error('帖子ID不存在');
       return;
     }
     const response = await axios.get(`/api/post-management/${post.postId}`);
     console.log('Detail response:', response.data);
     currentPost.value = {
       ...response.data,
       createdAt: response.data.createdAt || response.data.createTime || response.data.created_at,
       username: response.data.username || '未知用户',
       likeCount: response.data.like_count || 0,
       commentCount: response.data.comment_count || 0
     };
     dialogVisible.value = true;
     // 加载评论列表
     selectedPostId.value = post.postId;
     selectedPostTitle.value = post.title;
     commentPage.value = 1;
     await fetchComments();
   } catch (error) {
     console.error('获取详情失败:', error);
     ElMessage.error('获取详情失败，请重试');
   }
 };
 
 // 关闭弹窗
 const handleClose = (done) => {
   ElMessageBox.confirm('确认关闭？')
     .then(() => {
       done();
     })
     .catch(() => {});
 };
 
 // 分页处理
 const handleSizeChange = (val) => {
   pageSize.value = val;
   currentPage.value = 1; // 重置到第一页
   fetchPosts();
 };
 
 const handleCurrentChange = (val) => {
   currentPage.value = val;
   fetchPosts();
 };
 
 const handleCommentSizeChange = (newSize) => {
   commentSize.value = newSize;
   commentPage.value = 1;
   fetchComments();
 };
 
 const handleCommentCurrentChange = (newPage) => {
   commentPage.value = newPage;
   fetchComments();
 };
 
 onMounted(() => {
   fetchPosts();
 });
 </script>
 
 <style scoped>
 /* 整体布局和背景 */
 .post-management-container {
   padding: 20px;
   background-color: #f5f7fa;
   min-height: 100vh;
 }
 
 /* 标题区域 */
 .header-section {
   margin-bottom: 24px;
   padding-bottom: 15px;
   border-bottom: 1px solid #e6e9ed;
 }
 
 .header-section h2 {
   color: #1a2f54;
   font-weight: 600;
   font-size: 22px;
   margin-bottom: 8px;
 }
 
 .title-line {
   width: 50px;
   height: 4px;
   background: linear-gradient(90deg, #3b527a, #4e6694);
   border-radius: 2px;
 }
 
 /* 卡片通用样式 */
 .filter-card, .post-list-card {
   border-radius: 10px;
   margin-bottom: 24px;
   border: none;
   overflow: hidden;
   box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
 }
 
 /* 搜索卡片样式 */
 .filter-content {
   padding: 20px;
   display: flex;
   align-items: center;
   gap: 15px;
 }
 
 .filter-actions {
   display: flex;
   gap: 10px;
 }
 
 /* 按钮样式 */
 .custom-primary-button {
   background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
   border: none;
   color: white;
   transition: all 0.3s;
   box-shadow: 0 2px 6px rgba(26, 47, 84, 0.3);
 }
 
 .custom-primary-button:hover {
   background: linear-gradient(135deg, #3b527a 0%, #4e6694 100%);
   transform: translateY(-2px);
   box-shadow: 0 4px 8px rgba(26, 47, 84, 0.4);
 }
 
 .custom-reset-button {
   background: #f0f2f5;
   border-color: #dcdfe6;
   color: #606266;
   transition: all 0.3s;
 }
 
 .custom-reset-button:hover {
   background: #e4e7ed;
   color: #1a2f54;
 }
 
 /* 帖子列表卡片样式 */
 .post-list-card {
   position: relative;
 }
 
 .list-header {
   position: relative;
   padding: 16px 20px;
   display: flex;
   align-items: center;
   justify-content: space-between;
 }
 
 .list-header h3 {
   color: white;
   position: relative;
   z-index: 2;
   margin: 0;
   font-size: 18px;
   font-weight: 600;
 }
 
 .header-gradient {
   position: absolute;
   top: 0;
   left: 0;
   right: 0;
   height: 100%;
   background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
   z-index: 1;
 }
 
 .total-posts {
   position: relative;
   z-index: 2;
   color: white;
   font-size: 14px;
 }
 
 .total-posts .highlight {
   font-weight: bold;
   color: #ffd04b;
 }
 
 /* 表格样式 */
 .post-table {
   border-radius: 8px;
   overflow: hidden;
   margin: 0 20px;
 }
 
 :deep(.post-table .el-table__header) {
   background-color: #f0f5ff;
 }
 
 :deep(.post-table .el-table th) {
   background-color: #f0f5ff;
   color: #1a2f54;
   font-weight: 600;
   padding: 16px 12px;
   font-size: 14px;
 }
 
 :deep(.post-table .el-table td) {
   padding: 18px 12px;
   font-size: 14px;
   line-height: 1.5;
   vertical-align: middle;
 }
 
 :deep(.post-table .el-table td.el-table__cell) {
   border-bottom: 1px solid #f0f2f5;
 }
 
 :deep(.post-table .el-table__row) {
   transition: background-color 0.2s ease;
 }
 
 :deep(.post-table .el-table__row:hover) {
   background-color: #fafbfc;
 }
 
 /* 确保标题列有足够的内边距 */
 :deep(.post-table .el-table__cell:first-child) {
   padding-left: 20px;
 }
 
 :deep(.post-table .el-table__cell:last-child) {
   padding-right: 20px;
 }
 
 .action-buttons {
   display: flex;
   gap: 12px;
   flex-wrap: wrap;
   align-items: center;
 }
 
 .detail-button, .delete-button, .restore-button {
   padding: 8px 12px;
   border-radius: 6px;
   transition: all 0.3s ease;
   font-size: 13px;
   display: flex;
   align-items: center;
   gap: 4px;
   min-width: 80px;
   justify-content: center;
 }
 
 .detail-button {
   background-color: rgba(64, 158, 255, 0.1);
   color: #409eff;
 }
 
 .delete-button {
   background-color: rgba(245, 108, 108, 0.1);
   color: #f56c6c;
 }
 
 .restore-button {
   background-color: rgba(103, 194, 58, 0.1);
   color: #67c23a;
 }
 
 .detail-button:hover {
   background-color: rgba(64, 158, 255, 0.2);
 }
 
 .delete-button:hover {
   background-color: rgba(245, 108, 108, 0.2);
 }
 
 .restore-button:hover {
   background-color: rgba(103, 194, 58, 0.2);
 }
 
 .status-tag-table {
   padding: 6px 12px;
   font-size: 12px;
   font-weight: 500;
 }
 
 /* 分页样式 */
 .pagination-container {
   padding: 25px 20px;
   display: flex;
   justify-content: center;
   background-color: #fafbfc;
   border-top: 1px solid #f0f2f5;
 }
 
 /* 对话框样式 */
 .post-detail-dialog .post-detail-card {
   padding: 25px;
   background: #f9fafc;
   border-radius: 8px;
 }
 
 .post-header {
   display: flex;
   align-items: center;
   justify-content: space-between;
   margin-bottom: 25px;
   padding-bottom: 20px;
   border-bottom: 2px solid #e4e7ed;
 }
 
 .post-title {
   color: #1a2f54;
   font-size: 20px;
   font-weight: 600;
   margin: 0;
   line-height: 1.3;
 }
 
 .status-tag {
   font-size: 12px;
   padding: 6px 14px;
   font-weight: 500;
 }
 
 .post-meta-grid {
   display: grid;
   grid-template-columns: 1fr 1fr;
   gap: 20px;
   margin-bottom: 25px;
   padding: 20px;
   background: white;
   border-radius: 8px;
   border: 1px solid #e4e7ed;
 }
 
 .meta-item {
   display: flex;
   align-items: center;
   padding: 8px 0;
 }
 
 .meta-label {
   font-weight: 600;
   color: #606266;
   min-width: 90px;
   font-size: 14px;
 }
 
 .meta-value {
   color: #1a2f54;
   font-size: 14px;
 }
 
 .post-content h4 {
   color: #1a2f54;
   margin-bottom: 15px;
   font-size: 16px;
   font-weight: 600;
 }
 
 .content-box {
   background: white;
   padding: 20px;
   border-radius: 8px;
   border: 1px solid #e4e7ed;
   line-height: 1.6;
   color: #333;
   font-size: 14px;
   margin-bottom: 25px;
 }
 
 .comments-section {
   margin-top: 30px;
   padding-top: 25px;
   border-top: 2px solid #e4e7ed;
 }
 
 .comments-section h4 {
   color: #1a2f54;
   margin-bottom: 20px;
   font-size: 16px;
   font-weight: 600;
 }
 
 .comments-table {
   border-radius: 6px;
   overflow: hidden;
   margin-top: 15px;
 }
 
 :deep(.comments-table .el-table th) {
   background-color: #f8f9fa;
   color: #1a2f54;
   font-weight: 600;
   padding: 14px 12px;
   font-size: 13px;
 }
 
 :deep(.comments-table .el-table td) {
   padding: 16px 12px;
   font-size: 13px;
   line-height: 1.5;
 }
 
 :deep(.comments-table .el-table__row:hover) {
   background-color: #f9fafc;
 }
 
 .comment-actions {
   display: flex;
   gap: 10px;
   align-items: center;
 }
 
 .delete-comment-button, .restore-comment-button {
   padding: 6px 12px;
   border-radius: 4px;
   transition: all 0.3s ease;
   font-size: 12px;
   font-weight: 500;
   min-width: 50px;
   text-align: center;
 }
 
 .delete-comment-button {
   background-color: rgba(245, 108, 108, 0.1);
   color: #f56c6c;
 }
 
 .restore-comment-button {
   background-color: rgba(103, 194, 58, 0.1);
   color: #67c23a;
 }
 
 .delete-comment-button:hover {
   background-color: rgba(245, 108, 108, 0.2);
 }
 
 .restore-comment-button:hover {
   background-color: rgba(103, 194, 58, 0.2);
 }
 
 .dialog-footer {
   display: flex;
   justify-content: flex-end;
   gap: 12px;
   padding-top: 20px;
   margin-top: 25px;
   border-top: 1px solid #e4e7ed;
 }
 
 /* 响应式调整 */
 @media (max-width: 992px) {
   .filter-content {
     flex-direction: column;
     align-items: flex-start;
   }
   
   .post-meta-grid {
     grid-template-columns: 1fr;
   }
 }
 
 @media (max-width: 768px) {
   .action-buttons {
     flex-direction: column;
   }
   
   .list-header {
     flex-direction: column;
     align-items: flex-start;
     gap: 10px;
   }
 }
 </style>